#!/usr/local/bin/python
# -*- coding: utf-8 -*-
from datetime import datetime, date

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QAbstractItemView, QTableWidgetItem, QHeaderView
from dateutil.relativedelta import relativedelta
from xToolkit import xstring

import init
import ConfigManage
import initXirrPage
import toolkit
import  XirrWork
from data_alchemy.annual_yield_alchemy import AnnualYieldAlchemy
from data_alchemy.investment_flow_alchemy import InvestmentFlowAlchemy
from initLogger import logger
from ui.XirrWorkUI import Ui_XirrWork


class XirrWorkWidget(QWidget, Ui_XirrWork):
    '''
    类功能：展示年收益率界面
    '''

    def __init__(self):
        super(XirrWorkWidget, self).__init__()


        self.currentDate = datetime.now()
        #self.targetDate = self.currentDate - relativedelta(days=init.GO_DAYS)  # 记录当前系统查看数据的时间
        self.targetDate = self.currentDate

        self.setupUi(self)
        self.initXirrWorkUI()




    def initXirrWorkUI(self):
        '''
        函数功能：对年化收益率UI窗口进行初始化
        :return:
        '''

        #初始化页面标题
        self.initXirrWorkTitleUI()


        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        #初始化投资产品列表信息
        investmentProductList = ConfigManage.getInvestmentProductList()
        self.investment_product_comboBox.addItems(investmentProductList)

        #初始化日期编辑控件
        self.date_dateEdit.setCalendarPopup(True)
        self.date_dateEdit.setDate(self.targetDate)

        #初始化表格控件
        self.initXirrWorkTableUI()  #初始化XIRR数据表控件UI
        self.initXirrWorkTableData()  #初始化XIRR数据表控件数据
        self.initInvestmentFLowTableUI() #初始化投资数据流表控件UI
        self.initInvestmentFlowTableData()  #初始化投资数据流表控件数据

    def initXirrWorkTitleUI(self):
        '''
        函数功能:初始化页面标题
        :return:
        '''
        xirrWorkTitleStr = "%d年%d月投资收益" % (self.targetDate.year, self.targetDate.month)
        self.title_label.setText(xirrWorkTitleStr)



    def initXirrWorkTableUI(self):
        '''
        函数功能：对年化收益率表格进行初始化
        :return:
        '''
        logger.debug("call initXirrWorkTableUI function")

        self.xirr_tableWidget.setRowCount(initXirrPage.XIRR_TABLE_ROW_COUNT)  # 设置行数目
        self.xirr_tableWidget.setColumnCount(initXirrPage.XIRR_TABLE_COLUMN_COUNT)  # 设置列数目
        self.xirr_tableWidget.setHorizontalHeaderLabels(initXirrPage.XIRR_TABLE_COLUMN_CONTEXT)  # 设置列名

        self.xirr_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        # self.voucher_tableWidget.resizeColumnsToContents()  #设置列宽自适应
        self.xirr_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.xirr_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.xirr_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.xirr_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.xirr_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.xirr_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格


        self.xirr_tableWidget.setColumnWidth(0, 50)
        self.xirr_tableWidget.setColumnWidth(1, 50)
        self.xirr_tableWidget.setColumnWidth(2, 150)
        self.xirr_tableWidget.setColumnWidth(3, 250)


    def initInvestmentFLowTableUI(self):
        '''
        函数功能：对投资金额数据流表格进行初始化
        :return:
        '''
        logger.debug("call initInvestmentFLowTableUI function")

        self.investment_tableWidget.setRowCount(initXirrPage.INVESTMENT_TABLE_ROW_COUNT)  # 设置行数目
        self.investment_tableWidget.setColumnCount(initXirrPage.INVESTMENT_TABLE_COLUMN_COUNT)  # 设置列数目
        self.investment_tableWidget.setHorizontalHeaderLabels(initXirrPage.INVESTMENT_TABLE_COLUMN_CONTEXT)  # 设置列名

        self.investment_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        # self.voucher_tableWidget.resizeColumnsToContents()  #设置列宽自适应
        self.investment_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.investment_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.investment_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.investment_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.investment_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.investment_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格


        self.investment_tableWidget.setColumnWidth(0, 100)
        self.investment_tableWidget.setColumnWidth(1, 100)
        self.investment_tableWidget.setColumnWidth(2, 300)
        self.investment_tableWidget.setColumnWidth(3, 500)


    def initXirrWorkTableData(self):
        '''
        函数功能：对年化收益率表格进行数据初始化
        :return:
        '''
        self.showXirrTable(self.targetDate.year, self.targetDate.month)

    def initInvestmentFlowTableData(self):
        '''
        函数功能：对投资数据流表格进行数据初始化
        :return:
        '''
        self.showInvestmentFlowTable(self.targetDate.year, self.targetDate.month)


    def clearXirrTableContext(self):
        '''
        对XIRR表格中的内容进行清空
        :return:
        '''
        self.xirr_tableWidget.clear()
        self.xirr_tableWidget.setHorizontalHeaderLabels(initXirrPage.XIRR_TABLE_COLUMN_CONTEXT)
        self.initXirrWorkTableUI()

    def clearInvestmentFlowTableContext(self):
        '''
        函数功能：对投资数据流表中的数据进行清空
        :return:
        '''
        self.investment_tableWidget.clear()
        self.investment_tableWidget.setHorizontalHeaderLabels(initXirrPage.INVESTMENT_TABLE_COLUMN_CONTEXT)
        self.initInvestmentFLowTableUI()


    def onGoLastMonth(self):
        '''
        函数功能：“上个月”按钮的响应函数，展示上个月的数据
        :return:
        '''
        logger.debug("call onGoLastMonth  function")
        pass
        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))
        self.initXirrWorkTitleUI()  # 重新设置标题

        self.clearXirrTableContext()
        self.showXirrTable(self.targetDate.year, self.targetDate.month)

        self.clearInvestmentFlowTableContext()
        self.showInvestmentFlowTable(self.targetDate.year, self.targetDate.month)

    def onGoNextMonth(self):
        '''
        函数功能：“下个月”按钮的响应函数，展示下个月的数据
        :return:
        '''
        logger.debug("call onGoNextMonth function")

        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))
        self.initXirrWorkTitleUI()  #重新设置标题


        self.clearXirrTableContext()
        self.showXirrTable(self.targetDate.year, self.targetDate.month)

        self.clearInvestmentFlowTableContext()
        self.showInvestmentFlowTable(self.targetDate.year, self.targetDate.month)

    def onSearch(self):
        '''
        函数功能：查询按钮的响应函数
        :return:
        '''
        logger.debug("call onSearch function")

        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())
        self.targetDate = toolkit.setTargetDate(year, month)

        self.initXirrWorkTitleUI()

        self.clearXirrTableContext()
        self.showXirrTable(year, month)

        self.clearInvestmentFlowTableContext()
        self.showInvestmentFlowTable(year, month)




    def onUpdateAllDate(self):
        logger.debug("call onUpdateAllDate function")
        pass

    def onAdd(self):
        '''
        函数功能：“添加”按钮响应功能
        :return:
        '''
        logger.debug("call onAdd  function")

        investmentName =self.investment_product_comboBox.currentText()

        xirrDateStr = self.date_dateEdit.text()
        xirrDate = datetime.strptime(xirrDateStr, '%Y/%m/%d')

        finalValueStr = self.value_lineEdit.text()
        if(finalValueStr==''):
            finalValueFloat = 0.0
        else:
            finalValueFloat = float(finalValueStr.replace(",",""))

        XirrWork.generateProductAnnualYield(investmentName = investmentName,
                                   #finalDate=date(2023, 8, 13),
                                            finalDate = xirrDate,
                                            finalValue = finalValueFloat)

        self.onSearch()
        self.onClear()


    def onClear(self):
        '''
        函数功能：“清除”按钮响应函数，清除已填写数据
        :return:
        '''
        logger.debug("call onClear  function")

        self.date_dateEdit.setDate(self.targetDate)
        self.investment_product_comboBox.setCurrentIndex(0)
        self.value_lineEdit.clear()


    def showXirrTable(self, year, month):
        '''
        函数功能：展示个投资产品的xirr
        :return:
        '''

        logger.debug("call showXirrTable  function")

        annualYieldAlchemy = AnnualYieldAlchemy()

        investmentXirrInforList = annualYieldAlchemy.SearchInvestmentByMonth(year, month)
        #investmentXirrInforList = annualYieldAlchemy.SearchInvestmentByMonth(self.targetDate.year, 8)

        # 根据数据实际数量，对表格的行数进行重新设置
        self.xirr_tableWidget.setRowCount(len(investmentXirrInforList))
        i=0
        for investmentXirrInforItem in investmentXirrInforList:
            #序号
            noStr = "%d\t" % (i + 1)
            noItem = QTableWidgetItem(noStr)
            self.xirr_tableWidget.setItem(i, 0, noItem)

            #编号
            serialNumberStr = str(investmentXirrInforItem.id)
            serialNumberItem = QTableWidgetItem(serialNumberStr)
            self.xirr_tableWidget.setItem(i, 1, serialNumberItem)

            #日期
            observeDateStr = str(investmentXirrInforItem.observe_date)
            dateItem = QTableWidgetItem(observeDateStr)
            self.xirr_tableWidget.setItem(i, 2, dateItem)

            #产品名称
            productNameItem = QTableWidgetItem(investmentXirrInforItem.investment_name)
            self.xirr_tableWidget.setItem(i, 3, productNameItem)

            #存入总金额
            savedTotalMoneyStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.saved_total_money_value)).humanized_amount(complex=True)
            savedTotalMoneyStrWiggetItem = QTableWidgetItem(savedTotalMoneyStr)
            self.xirr_tableWidget.setItem(i, 4, savedTotalMoneyStrWiggetItem)

            #提取总金额
            drawedTotalMoneyStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.drawed_total_money_value)).humanized_amount(complex=True)
            drawedTotalMoneyStrWiggetItem = QTableWidgetItem(drawedTotalMoneyStr)
            self.xirr_tableWidget.setItem(i, 5, drawedTotalMoneyStrWiggetItem)


            #分红总金额
            dividendTotalMoneyStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.dividend_total_value)).humanized_amount(complex=True)
            dividendTotalMoneyStrWiggetItem = QTableWidgetItem(dividendTotalMoneyStr)
            self.xirr_tableWidget.setItem(i, 6, dividendTotalMoneyStrWiggetItem)

            #现存总金额
            currentTotalMoneyStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.current_real_total_value)).humanized_amount(complex=True)
            currentTotalMoneyStrWiggetItem = QTableWidgetItem(currentTotalMoneyStr)
            self.xirr_tableWidget.setItem(i, 7, currentTotalMoneyStrWiggetItem)

            #现存本金金额
            currentPrincipalTotalMoneyStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.current_principal_total_value)).humanized_amount(complex=True)
            currentPrincipalTotalMoneyWiggetItem = QTableWidgetItem(currentPrincipalTotalMoneyStr)
            self.xirr_tableWidget.setItem(i, 8, currentPrincipalTotalMoneyWiggetItem)

            #总收益金额
            earningsTotalMoneyStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.earnings_total_value)).humanized_amount(complex=True)
            earningsTotalMoneyWiggetItem = QTableWidgetItem(earningsTotalMoneyStr)
            self.xirr_tableWidget.setItem(i, 9, earningsTotalMoneyWiggetItem)

            #年化收益率
            xirrValueStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.xirr_value * 100)).humanized_amount(complex=True)
            xirrValueWiggetItem = QTableWidgetItem(xirrValueStr+"%")
            self.xirr_tableWidget.setItem(i, 10, xirrValueWiggetItem)

            #总收益率
            totalYieldRateValueStr = xstring.dispose(toolkit.processValueSignificant(investmentXirrInforItem.total_yield_rate_value * 100)).humanized_amount(complex=True)
            totalYieldRateValueWiggetItem = QTableWidgetItem(totalYieldRateValueStr+"%")
            self.xirr_tableWidget.setItem(i, 11, totalYieldRateValueWiggetItem)

            i=i+1

        self.xirr_tableWidget.resizeRowsToContents()  # 设置行宽自适应

    def showInvestmentFlowTable(self, year, month):
        '''
        函数功能；以表格形式展示投资金额流数据
        :param year:
        :param month:
        :return:
        '''

        logger.debug("call showInvestmentFlowTable  function")

        investmentFlowAlchemy = InvestmentFlowAlchemy()
        investmentFlowInforList =  investmentFlowAlchemy.SearchInvestmentFlowByMonth(year, month)

        # 根据数据实际数量，对表格的行数进行重新设置
        self.investment_tableWidget.setRowCount(len(investmentFlowInforList))
        i=0

        for investmentFlowInforItem in investmentFlowInforList:
            #序号
            noStr = "%d\t" % (i + 1)
            noItem = QTableWidgetItem(noStr)
            self.investment_tableWidget.setItem(i, 0, noItem)

            #编号
            serialNumberStr = str(investmentFlowInforItem.id)
            serialNumberItem = QTableWidgetItem(serialNumberStr)
            self.investment_tableWidget.setItem(i, 1, serialNumberItem)

            #日期
            investmentDateStr = str(investmentFlowInforItem.investment_date)
            dateItem = QTableWidgetItem(investmentDateStr)
            self.investment_tableWidget.setItem(i, 2, dateItem)

            #产品名称
            productNameItem = QTableWidgetItem(investmentFlowInforItem.investment_name)
            self.investment_tableWidget.setItem(i, 3, productNameItem)

            #金额
            investmentValueStr = xstring.dispose(toolkit.processValueSignificant(investmentFlowInforItem.investment_value)).humanized_amount(complex=True)
            investmentValueStrWiggetItem = QTableWidgetItem(investmentValueStr)
            self.investment_tableWidget.setItem(i, 4, investmentValueStrWiggetItem)

            #类型
            flowTypeItem = QTableWidgetItem(investmentFlowInforItem.flow_type)
            self.investment_tableWidget.setItem(i, 5, flowTypeItem)


            #记账凭证编号
            voucherIdStr = str(investmentFlowInforItem.voucher_id)
            voucherIdItem = QTableWidgetItem(voucherIdStr )
            self.investment_tableWidget.setItem(i, 6, voucherIdItem)

            i = i + 1
        self.investment_tableWidget.resizeRowsToContents()  # 设置行宽自适应